#!/usr/bin/env python
# coding: utf-8
# 获取10分钟内最新的一条消息
import random
import sqlite3

import requests
import time
# from config import last_update_time,DB_PATH

last_update_time = time.time()-3000
base_url = "https://www.cls.cn/nodeapi/updateTelegraphList"

params = {
    "app": "CailianpressWeb",
    "category": "",
    "hasFirstVipArticle": 1,
    "lastTime": str(last_update_time),
    "os": "web",
    "rn": "20",
    "subscribedColumnIds": "",
    "sv": "7.5.5",
    "sign": "9fa0d3f7fcb3d39a4ca734c543f99d03",
}

header = {
    "Host": "www.cls.cn",
    "Connection": "keep-alive",
    "sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
    "Accept": 'application/json, text/plain, */*',
    "sec-ch-ua-mobile": '?0',
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36",
    "Content-Type": "application/json;charset=utf-8",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://www.cls.cn/",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cookie": "HWWAFSESID=2d39e9747745a7ca5e; HWWAFSESTIME=1620959717642; hasTelegraphRemind=on; hasTelegraphSound=on; vipNotificationState=on; Hm_lvt_fa5455bb5e9f0f260c32a1d45603ba3e=1620959719; hasTelegraphNotification=off; Hm_lpvt_fa5455bb5e9f0f260c32a1d45603ba3e=1620961307",
    "If-None-Match": 'W/"3f-WG/1HjmC3FTHAG8QCCJGb5w1iSY"',
}

def get_news():
    time.sleep(random.randint(2, 8))
    res = requests.get(url=base_url, params=params, headers=header)
    if res.status_code == 304:
        return 304
    elif res.status_code == 200:
        news_list = []
        dict_res = dict(res.json())
        # print(dict_res)
        roll_data_list = dict_res["data"]["roll_data"]
        for roll_data in roll_data_list:
            ctime = roll_data["ctime"]
            content = roll_data["content"]
            share_url = roll_data["shareurl"]
            brief = roll_data.get("brief", "财联社")
            # 保存到 sqlite3 中
            # save_inf_to_sqlite(ctime, content, share_url, brief)
            time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ctime))
            news_list.append({"ctime":time_str, "content":content, "share_url":share_url, "brief":brief})
        # 按照时间降序排列
        news_list2 = sorted(news_list,key=lambda x: (x['ctime']), reverse=True)
        return news_list2


if __name__ == '__main__':
    result = get_news()
    print(result)
